// pages/pingtuan/pingtuan-detail/pingtuan-detail.js
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    modalHidden: true,
    index: 0, //商品有人拼单
    modal_sum: 1,
    modal_id: 0,
    ren: 2,
    i: 1,
    ll: 0,
    mm: 0,
    mmm: true,
    iii:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options.name)
    console.log(options.id)
    if(options.name == undefined || options.id!=undefined){
      this.setData({
        iii:1
      })
    }
    if(this.data.iii == 1){
      let tableName = 'pingtuan'
      // 实例化查询对象
      let query = new wx.BaaS.Query()
  
      // 设置查询条件（比较、字符串包含、组合等）
      //...
      query.compare('product_code', '=', options.id)
  
      // 应用查询对象
      let Product = new wx.BaaS.TableObject(tableName)
      Product.setQuery(query).find().then(res => {
        // success
        console.log(res.data.objects)
        if (res.data.objects != []) {
          this.setData({
            up: res.data.objects.length
          })
          var items = []
          var max = []
          var sum = 0
          for (var i = 0; i < res.data.objects.length; i++) {
            if (res.data.objects[i].isOrder == 0) { //正在拼单
              items.push(res.data.objects[i])
            } else {
              sum++
            }
          }
          console.log(items)
          var kkk = this.quickSort(items)
          console.log(kkk)
          if (kkk[0].iphone == wx.getStorageSync('phone')) {
            this.setData({
              ll: 1,
              mm: 1
            })
          } else {
            for (var i = 0; i < kkk[0].phone.length; i++) {
              if (kkk[0].phone == wx.getStorageSync('phone')) {
                this.setData({
                  mm: 1
                })
              }
            }
          }
          this.setData({
            items: kkk,
            item: kkk[0],
            sum: sum //正在拼单列表
          })
        } else {
          this.setData({
            index: 1 //商品无人拼单
          })
        }
        this.chuli(0)
      }, err => {
        // err
      })
      var product = app.globalData.product
      console.log(product)
  
      for (var i = 0; i < product.length; i++) {
        if (product[i].product_code == options.id) {
          this.setData({
            product_item: product[i]
          })
        }
      }
      var item = this.data.product_item.modal_cost_advise
  
      this.setData({
        modal_total: item[1],
      })
  
    }else{
      let tableName = 'pingtuan'
      // 实例化查询对象
      let query = new wx.BaaS.Query()
  
      // 设置查询条件（比较、字符串包含、组合等）
      //...
      query.compare('id', '=', options.name)
  
      // 应用查询对象
      let Product = new wx.BaaS.TableObject(tableName)
      Product.setQuery(query).find().then(res => {
        console.log(res.data.objects[0])
        var product = app.globalData.product
        console.log(product)
    
        for (var i = 0; i < product.length; i++) {
          if (product[i].product_code == res.data.objects[0].product_code) {
            this.setData({
              product_item: product[i]
            })
          }
        }
        var kkk = res.data.objects
        console.log(kkk)
        if (kkk[0].iphone == wx.getStorageSync('phone')) {
          this.setData({
            ll: 1,
            mm: 1
          })
        } else {
          for (var i = 0; i < kkk[0].phone.length; i++) {
            if (kkk[0].phone == wx.getStorageSync('phone')) {
              this.setData({
                mm: 1
              })
            }
          }
        }
        this.setData({
          item:kkk[0],
          // sum: sum, //正在拼单列表
          index:0
        })
      this.chuli(0)
      }, err => {
        // err
      })
    }
   
  },
  quxiao:function(e){
    this.setData({
      mmm:false
    })
  },
  quxiao22(){
    this.setData({
      mmm:true
    })
  },
  quxiao11: function (e) {
    if (this.data.ll == 1) {
      let tableName = 'pingtuan'
      // 实例化查询对象
      let query = new wx.BaaS.Query()

      // 设置查询条件（比较、字符串包含、组合等）
      //...
      query.compare('product_code', '=', this.data.product_item.product_code)
      query.compare('iphone', '=', wx.getStorageSync('phone'))
      // 应用查询对象
      let Product = new wx.BaaS.TableObject(tableName)
      Product.setQuery(query).find().then(res => {
        // success
        console.log(res.data.objects)
        if (res.data.objects[0].phone[1] != undefined) {
          var qq = res.data.objects[0].phone
          var iphone = res.data.objects[0].phone[1]
          console.log(qq)
          console.log(iphone)
          var q = []
          var n = []
          var p = []
          var m = []
          for (var i = 1; i < qq.length; i++) {
            q.push(qq[i])
            n.push(res.data.objects[0].name[i])
            p.push(res.data.objects[0].content[i])
            m.push(res.data.objects[0].img[i])
          }
          console.log(q)

          let tableName = 'pingtuan'
          let recordID = this.data.item.id // 数据行 id

          let Product = new wx.BaaS.TableObject(tableName)
          let product = Product.getWithoutData(recordID)

          product.set('phone', q)
          product.set('name', n)
          product.set('content', p)
          product.append('img', m)

          // product.append('phone', wx.getStorageSync('phone'))
          product.update().then(res => {
            // success
            console.log(res)
          }, err => {
            // err
          })
        } else {
          let tableName = 'pingtuan'
          let recordID = this.data.item._id

          let Product = new wx.BaaS.TableObject(tableName)
          Product.delete(recordID).then(res => {
            // success
            wx.showToast({
              title: '取消成功',
            })
          }, err => {
            // err
          })
        }
      }, err => {

      })

    }
    this.setData({
      mmm:true
    })
  },
  xuan: function (e) {
    console.log(e.currentTarget.dataset.postid)

    this.setData({
      ren: parseInt(e.currentTarget.dataset.postid)
    })

  },
  quickSort: function (arr) {

    if (arr.length <= 1) {
      return arr;
    }

    var pivotIndex = Math.floor(arr.length / 2);

    var pivot = arr.splice(pivotIndex, 1)[0];

    var left = [];

    var right = [];

    for (var i = 0; i < arr.length; i++) {

      if (arr[i] < pivot || arr[i].ren == 2) {

        left.push(arr[i]);

      } else {

        right.push(arr[i]);

      }

    }

    return this.quickSort(left).concat([pivot], this.quickSort(right));

  },
  onShareAppMessage: function (options) {

    var that = this

    // 来自页面内的按钮的转发
    if (options.from == 'button') {
      console.log(res.target); // shareBtn
      // 此处可以修改 shareObj 中的内容

    };
    // 返回shareObj
    return {
      title: that.data.name,
      path: '/pages/post-detail/post-detail',
      imageUrl: this.data.product_item.product_swiper_pic1
    };
  },
  onShareTap: function (e) {
    var that = this
    var itemList = [
      "分享给微信好友",
      "分享到朋友圈",
    ]

    wx.showActionSheet({
      itemList: itemList,
      itemColor: "#405f80",
      success: function (res) {
        wx.showModal({
          title: '用户' + itemList[res.tapIndex],
          content: ' 是否分享？',
          success(res) {
            if (res.confirm) {
              console.log('用户点击确定')
              that.onShareAppMessage()
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })

      }
    })
  },
  onAddress: function (e) {
    wx.navigateTo({
      url: '/pages/addresDetail/addresDetail',
    })
  },
  xiafan(e) {
    console.log(111)
    this.chuli(this.data.id + 1)
  },
  chuli(id) {
    if(this.data.iii == 0){
      this.setData({
        items:[this.data.item]
      })
    }
    var that = this
    console.log(that.data.items[id].img[1])
    that.setData({
      firsts_rectangle: that.data.items[id].phone.length / that.data.items[id].ren * 100,
      cha: that.data.items[id].ren - that.data.items[id].phone.length,
      img: that.data.items[id].img,
      item: that.data.items[id],
      has: that.data.items[id].phone.length,
      id: that.data.items[id]._id
    })
  },
  faqi: function (e) {

    var items = []
    for (var i = 0; i < this.data.product_item.modal_cost_advise.length; i++) {
      var modal_cost_advise = this.data.product_item.modal_cost_advise[i].split(',')
      var item = {
        modal_cost: app.cost(wx.getStorageSync('dengji'),modal_cost_advise[0]),
        modal_total: modal_cost_advise[1]
      }
      items.push(item)
    }
    console.log(items)
    this.setData({
      modal: items,
      modal_cost: items[0].modal_cost,
      cost: items[0].modal_cost
    })
    this.setData({
      modalHidden: false,
      kkk: 1
    })

  },
  canjia: function (e) {
    console.log(11)
    var items = []
    for (var i = 0; i < this.data.product_item.modal_cost_advise.length; i++) {
      var modal_cost_advise = this.data.product_item.modal_cost_advise[i].split(',')
      var item = {
        modal_cost: modal_cost_advise[0],
        modal_total: modal_cost_advise[1]
      }
      items.push(item)
    }


    console.log(items)
    this.setData({
      modal: items,
      modal_cost: items[0].modal_cost,
      cost: items[0].modal_cost
    })
    this.setData({
      modalHidden: false,
      kkk: 0
    })
  },

  modalCandel: function (e) {
    this.setData({
      modalHidden: true,

    })
  },
  odalConfirm: function (e) {
    console.log(this.data.modal[this.data.modal_id])
    var c = this.data.modal_cost  + ',' + this.data.modal[this.data.modal_id].modal_total + ',' + this.data.modal_sum.toString()
    console.log(c)

    let tableName = 'pingtuan'
    let recordID = this.data.id // 数据行 id

    let Product = new wx.BaaS.TableObject(tableName)
    let product = Product.getWithoutData(recordID)

    product.append('phone', wx.getStorageSync('phone'))
    product.append('name', wx.getStorageSync('nickName'))
    product.append('content', c)
    product.append('img', wx.getStorageSync('avatarUrl'))
    if (this.data.item.phone.length + 1 == this.data.item.ren) {
      product.set('isOrder', 1)
    }
    // product.append('phone', wx.getStorageSync('phone'))
    product.update().then(res => {
      // success
      console.log(res)
    }, err => {
      // err
    })
    this.setData({
      modalHidden: true
    })
  },
  modalConfirm: function (e) {
    console.log(this.data.modal[this.data.modal_id])
    var c = this.data.modal_cost  + ',' + this.data.modal[this.data.modal_id].modal_total + ',' + this.data.modal_sum.toString()
    console.log(c)
    this.setData({
      i: 0
    })
    if (this.data.i == 0) {
      let tableName = 'pingtuan'
      let Product = new wx.BaaS.TableObject(tableName)
      let product = Product.create()
      var name = []
      name.push(wx.getStorageSync('nickName'))
      var date = new Date()
      var year = date.getFullYear();
      var mouth = date.getMonth();
      var day = date.getDay()
      console.log(year + '-' + mouth + '-' + day)
      // 设置方式一
      let apple = {
        phone: [wx.getStorageSync('phone')],
        name: name,
        product_code: this.data.product_item.product_code,
        iphone: wx.getStorageSync('phone'),
        ren: this.data.ren,
        img: [wx.getStorageSync('avatarUrl')],
        content: [c]
      }

      console.log(apple)
      product.set(apple).save().then(res => {
        // success
        wx.showToast({
          title: '您的拼团已创建成功,可以在个人主页查看信息,拼单成功后为您发送短信通知',
          icon: 'none',
          duration: 1000
        })
        var ppp = [this.data.product_item.product_name]
        app.getMessage(wx.getStorageSync('phone'), '5445', ppp)
        console.log(res)
      }, err => {
        wx.showToast({
          title: '您的拼团创建失败',
          icon: 'none',
          duration: 1000
        })
        //err 为 HError 对象
      })
      this.setData({
        modalHidden: true
      })
    }
  },
  GoDetail: function (e) {
    var postid = e.currentTarget.dataset.postid
    console.log(this.data.modal[postid])
    this.setData({
      modal_cost: this.data.modal[postid].modal_cost,
      modal_id: postid
    })
    console.log(this.data.modal_cost);
  },
  addCount(e) {

    let num = this.data.modal_sum;
    if (num >= 5) {
      wx.showToast({
        title: '已经是最多数量啦',
        icon: 'none'
      })
    } else {
      num = num + 1;
    }
    this.setData({
      modal_cost: (num * parseInt(this.data.cost )).toString(),
      modal_sum: num
    });

  },
  // 减少数量
  minusCount(e) {
    let num = this.data.modal_sum;
    if (num <= 1) {
      wx.showToast({
        title: '已经是最少数量啦',
        icon: 'none'
      })
    } else {
      num = num - 1;
    }
    this.setData({
      modal_cost: (num * parseInt(this.data.cost )).toString(),
      modal_sum: num
    });

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})